const { secret } = require('../../config/global');
// const md5 = require('md5');
// 导入jwt
const jwt = require('jsonwebtoken');
// 导入数据库查询方法
const { add, getOne } = require('../../utils/dbTools');
const { verifyToken } = require('../../utils/util')

// 数据表名称
// 员工表
const staffTable = 'staff';
// 机构表
const businessTableName = 'business';
// 随机短信验证码
var randMsgCode;
// 登录处理函数
const login = async (req, res) => {
    const output = {
        code: 200,
        msg: '登录成功'
    }
    // 获取请求参数
    let { phone, msgCode } = req.body;
    // 根据用户类型区分到底是员工还是患者
    var tableName = staffTable;
    if (!phone || !msgCode) {
        output.code = 500;
        output.msg = '参数错误: 未提phone, msgCode';
        return res.send(output);
    }
    if (randMsgCode != msgCode) {
        output.code = 500;
        output.msg = '验证码错误';
        return res.send(output);
    }
    // 对密码进行MD5加密
    // password = md5(password.toString());
    var result = await getOne(tableName, { phone });
    if (!result) {
        // 账号不存在: 自动注册账号
        const { insertId } = await add({ phone, create_time: Date.now() }, tableName);
        // 默认注册账号rid=1
        result = { id: insertId, role_id: 1, phone }
    } else {
        if (result.status === 2) {
            output.code = 500;
            output.msg = '账号被禁用';
            return res.send(output);
        }
        // 查询机构信息
        if (result.bus_id) {
            const { title: bus_title } = await getOne(businessTableName, { id: result.bus_id });
            result.bus_title = bus_title;
        }
    }
    const { id, role_id } = result
    // 生成登录凭证token
    const token = jwt.sign({ id, role_id, phone }, secret, { expiresIn: 60 });
    // 生成refresh_token
    const refresh_token = jwt.sign({ id, role_id, phone }, secret, { expiresIn: '2h' });
    output.data = {
        ...result,
        token,
        refresh_token
    }

    // 删除密码
    delete output.data.password;
    res.send(output);
}

// 发送短信验证码
const getMsgCode = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { phone } = req.query;
    if (!phone) {
        output.code = 500;
        output.msg = '参数错误';
        return res.send(output);
    }
    randMsgCode = Date.now().toString().slice(9, 13);
    output.data = randMsgCode;
    res.send(output);
}


// 检查token是否过期
const checkToken = async (req, res) => {
    const { authorization } = req.headers;
    // 验证token是否合法
    const output = verifyToken(authorization)
    res.send(output);
}

// token续费
const refreshToken = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    // 获取refresh_token
    const refresh_token = req.body.refresh_token;
    try {
        // 解析refresh_token
        var decoded = jwt.verify(refresh_token, secret);
        if (!decoded) {
            output.code = 405;
            output.msg = 'refresh_token不合法或已过期';
            return res.send(output);
        }
        // refresh_token中保存的数据{id,role_id,phone}
        const { id, role_id, phone } = decoded
        // 重新生成token
        const newToken = jwt.sign({ id, role_id, phone }, secret, { expiresIn: '1h' });
        // 重新生成refresh_token
        const newRefreshToken = jwt.sign({ id, role_id, phone }, secret, { expiresIn: '2h' });
        output.data = {
            token: newToken, refresh_token: newRefreshToken
        }
        return res.send(output)
    } catch (err) {
        // err
        if (!decoded) {
            output.code = 405;
            output.msg = 'refresh_token不合法或已过期';
            return res.send(output);
        }
    }
    res.send(output)
}


module.exports = {
    login, getMsgCode, checkToken, refreshToken
};